package utils;

import android.util.Log;


import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
 * Created by sunsh on 2017/12/2.
 */

public class OkhttpUtils {

    public static String TAG ="OkhttpUtils";
    private static OkhttpUtils instance=new OkhttpUtils();

    private final OkHttpClient client = new OkHttpClient();
    private final Gson gson = new Gson();
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    File sdcache = getExternalCacheDir();
    public void init(){
//        client.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));

    }

    private File getExternalCacheDir() {
     return new File("F:/");
    }

    public static OkhttpUtils getInstance() {

        return instance;
    }
    /**
     * 同步Get方法
     */
    private void okHttp_synchronousGet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = "https://api.github.com/";
                    OkHttpClient client = new OkHttpClient();
//                    Request request = new Request.Builder().url(url).cacheControl(new CacheControl().build();
                    Request request = new Request.Builder().url(url).build();
                    okhttp3.Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.i(TAG, response.body().string());
                    } else {
                        Log.i(TAG, "okHttp is request error");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }




    public void asyncGet(){
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request =new Request.Builder()
                 .url("http://blog.csdn.net/lmj623565791/article/details/47911083")
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("Accept", "application/json; q=0.5")
                .addHeader("Accept", "application/vnd.github.v3+json")

                .build();
        Call call =mOkHttpClient.newCall(request);
        // 异步执行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String s = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                        }

                    });
                }
            }

        });


    }


    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
                    String url = "http://api.k780.com:88/";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    String json = "{'app':'weather.future','weaid':'1','appkey':'10003'," +
                            "'sign':'b59bc3ef6191eb9f747dd4e83c99f2a4','format':'json'}";
                    RequestBody formBody = new FormBody.Builder()
                            .add("app", "weather.future")
                            .add("weaid", "1")
                            .add("appkey", "10003")
                            .add("sign",
                                    "b59bc3ef6191eb9f747dd4e83c99f2a4")
                            .add("format", "json")
                            .build();
                    Request request = new Request.Builder().url(url).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    Log.i(TAG, response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");

    public void postString() throws IOException {

            String postBody = ""
                    + "Releases\n"
                    + "--------\n"
                    + "\n"
                    + " * _1.0_ May 6, 2013\n"
                    + " * _1.1_ June 15, 2013\n"
                    + " * _1.2_ August 11, 2013\n";

            Request request = new Request.Builder()
                    .url("https://api.github.com/markdown/raw")
                    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
                    .build();

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println(response.body().string());



    }

    public void postStream() throws IOException {

            RequestBody requestBody = new RequestBody() {
                @Override public MediaType contentType() {
                    return MEDIA_TYPE_MARKDOWN;
                }

                @Override
                public void writeTo(BufferedSink sink) throws IOException {
                    sink.writeUtf8("Numbers\n");
                    sink.writeUtf8("-------\n");
                    for (int i = 2; i <= 997; i++) {
                        sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
                    }
                }

                private String factor(int n) {
                    for (int i = 2; i < n; i++) {
                        int x = n / i;
                        if (x * i == n) return factor(x) + " × " + i;
                    }
                    return Integer.toString(n);
                }
            };

            Request request = new Request.Builder()
                    .url("https://api.github.com/markdown/raw")
                    .post(requestBody)
                    .build();

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println(response.body().string());

    }

   public void postFile() throws IOException {
       File file = new File("README.md");

       Request request = new Request.Builder()
               .url("https://api.github.com/markdown/raw")
               .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
               .build();

       Response response = client.newCall(request).execute();
       if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

       System.out.println(response.body().string());

    }

     private void gsonGet() throws IOException {
         Request request = new Request.Builder()
                 .url("https://api.github.com/gists/c2a7c39532239ff261be")
                 .build();
         Response response = client.newCall(request).execute();
         if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

         Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
         for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
             System.out.println(entry.getKey());
             System.out.println(entry.getValue().content);
         }
     }


  static class Gist {
    Map<String, GistFile> files;
}

  static class GistFile {
    String content;
   }
//
//
//
//    public void gsonGet(){
//
//
//
//    }
//    public void gsonGet(){
//
//
//
//    }
//    public void gsonGet(){
//
//
//
//    }



    private void runOnUiThread(Runnable runnable)  {



    }




}
